/*
 * Score.cpp
 *
 *  Created on: 2013. 10. 30.
 *      Author: mega@gamevil.com
 */

#include "../User.h"
#include "Score.h"
#include "Static.h"
#include "Memcached.h"
#include "../NResource/Static.h"
#include "Function.h"

#include <sstream>

namespace ProjectZ { namespace NLogic {

Score::Score(User * pUser)
{
	_user = pUser;
}

Score::~Score()
{

}

void
Score::Initialize()
{
	_data.Clear();
	_medal.Clear();
}

void
Score::Finalize()
{

}

void
Score::SetMemcache()
{
	_data.wp_last_week		= _user->GetUserInfo().wp_last_week;
	_data.wp_cur_week		= _user->GetUserInfo().wp_cur_week;
	_data.wp_reg_date		= _user->GetUserInfo().wp_reg_date;
	_data.wp_last_reg_date	= _user->GetUserInfo().wp_last_reg_date;

	::ProjectZ::NLogic::Memcached * clsMemcached = ::ProjectZ::NLogic::Static::Instance().GETMEMCACHED();
	clsMemcached->Set(_user->GetMemKey()->GetData()->_score.c_str(), reinterpret_cast<char *>(&_data), sizeof(Data), 0);
}

void
Score::SetRedis(int winPoint)
{
	if (0 == winPoint)
		return;

	if (false == NResource::Static::InstancePtr()->GetEventTime()->IsPVPWorldRankingEvent(_user))
		return;

	_user->GetUserInfo().reserve1 += winPoint;
	if (_user->GetUserInfo().reserve1 < 0)
		_user->GetUserInfo().reserve1 = 0;

	_user->FlushUserInfoCache();

	::NoSQL::Command::Redis clsRedis;
	clsRedis._eServer = ::NoSQL::Command::BaseInfo::REDIS;
	clsRedis._eAction = ::NoSQL::Command::Redis::ZADD;
	clsRedis._key = "PVP_RANK";
	clsRedis._value = std::to_string(_user->GetUserSeq()).c_str();
	clsRedis._score = _user->GetUserInfo().reserve1;

	::NoSQL::Command::Auto clsAuto(::NoSQL::GETCOMMANDPOOL());
	clsAuto->SetRedis(clsRedis);

	::NoSQL::SESSION()->SyncExecute(static_cast<int>(RedisServerType::PVP_MASTER), clsAuto);
}

void
Score::SetMedalMemcached()
{
	::ProjectZ::NLogic::Memcached * clsMemcached = ::ProjectZ::NLogic::Static::Instance().GETMEMCACHED();
	clsMemcached->Set(_user->GetMemKey()->GetData()->_medal.c_str(), reinterpret_cast<char *>(&_medal), sizeof(Medal), 0);
}

void
Score::LoadMedal()
{
	std::vector<int> medalVector;
	NLogic::NFunction::StringToIntSplit(_user->GetUserInfo().medal, ',', medalVector);

	DEBUGLOG("medal userseq:%d _user->GetUserInfo().medal %s", _user->GetUserSeq(), _user->GetUserInfo().medal.c_str());
	DEBUGLOG("medal userseq:%d medalVector size %d", _user->GetUserSeq(), medalVector.size());
	auto iter = medalVector.begin();
	for (int i=0; iter != medalVector.end(); ++iter, i++)
	{
		switch(i)
		{
		case 0:
			_medal.gold = medalVector[0];
			break;
		case 1:
			_medal.silver = medalVector[1];
			break;
		case 2:
			_medal.bronze = medalVector[2];
			break;
		}
	}

	DEBUGLOG("load medal userseq:%d gold:%d silver:%d bronze:%d", _user->GetUserSeq(), _medal.gold, _medal.silver, _medal.bronze);
}

void
Score::SaveMedal()
{
	std::stringstream stream;

	stream << _medal.gold << "," << _medal.silver << "," << _medal.bronze;
	_user->GetUserInfo().medal = stream.str().c_str();
}

} /* namespace NLogic */ } /* namespace ProjectZ */
